package com.qc.sys.web;

import com.qc.common.config.Global;
import com.qc.common.security.shiro.session.SessionDAO;
import com.qc.common.utils.CookieUtils;
import com.qc.common.utils.StringUtils;
import com.qc.common.web.BaseController;
import com.qc.sys.entity.User;
import com.qc.sys.security.SystemAuthorizingRealm;
import com.qc.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录Controller
 */
@Controller
public class LoginController extends BaseController {
	
	@Autowired
	private SessionDAO sessionDAO;

	/**
	 * 管理登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		User principal = UserUtils.getCurrentUser();

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			CookieUtils.setCookie(response, "LOGINED", "false");
		}
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			return "redirect:/" ;
		}
		return "login";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "/")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		User principal = UserUtils.getCurrentUser();

		// 登录成功后，验证码计算器清零
		UserUtils.isValidateCodeLogin(principal.getName(), false, true);
		
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)){
				CookieUtils.setCookie(response, "LOGINED", "true");
			}else if (StringUtils.equals(logined, "true")){
				UserUtils.getSubject().logout();
				return "redirect:/login";
			}
		}
		setTitle(model, "主页");
		return renderString("sys.main.home",request,response, principal);
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "loginOut")
	public String loginOut() {
		UserUtils.clearCache();
		UserUtils.getSubject().logout();
		return "redirect:/login";
	}
}
